<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="物料编码" prop="cfmaterialnumber">
        <el-input
          v-model="queryParams.cfmaterialnumber"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="cfmaterialname">
        <el-input
          v-model="queryParams.cfmaterialname"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否手工新增" prop="cfverson" label-width="100px">
        <el-select v-model="queryParams.cfverson" placeholder="请选择是否手工新增" clearable>
          <el-option
            v-for="dict in dict.type.yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="车间" prop="cfworkshopid">-->
<!--        <el-select v-model="queryParams.cfworkshopid" placeholder="车间" @keyup.enter.native="handleQuery" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.bom_plant"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bomcostestimation/basedocument:materialhalf:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bomcostestimation/basedocument:materialhalf:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bomcostestimation/basedocument:materialhalf:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="synchronizeData"
          v-hasPermi="['bomcostestimation/basedocument:materialhalf:add']"
        >手工同步</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bomcostestimation/basedocument:materialhalf:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"  border stripe :data="materialhalfList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料编码" align="center" prop="cfmaterialnumber" />
      <el-table-column label="物料名称" align="center" prop="cfmaterialname" />
      <el-table-column label="计量单位" align="center" prop="cfmaterialunit" />
      <el-table-column label="规格型号" align="center" prop="cfmaterialspecification" />
      <el-table-column label="生产量" align="center" prop="cfproductionquantity" />
      <el-table-column label="描述" align="center" prop="fdescription" />
      <el-table-column label="是否手工新增" align="center" prop="cfverson" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_no" :value="scope.row.cfverson"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['bomcostestimation/basedocument:materialhalf:edit']"-->
<!--          >修改</el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['bomcostestimation/basedocument:materialhalf:remove']"-->
<!--          >删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料BOM对话框 -->
    <el-dialog :title="title" v-drag :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="cfmaterialnumber">
              <el-input v-model="form.cfmaterialnumber" placeholder="请输入物料编码" readonly/>
              <span class="el-input__suffix">
                <span class="el-input__suffix-inner">
                  <i class="el-input_icon icon el-icon-search"
                     onmousemove="this.style.color='#366EDD'"
                     onmouseout="this.style.color='#919191'"
                     style="font-size: 16px;
                            position: absolute;
                            cursor: pointer;
                            right: 20px;
                            top: 10px;
                            background-color: #ffffff;"
                     @click="openF7('specialmaterial',false,null)"
                  />
                </span>
          </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="cfmaterialname">
              <el-input v-model="form.cfmaterialname" placeholder="请输入物料名称" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="cfmaterialunit">
              <el-input v-model="form.cfmaterialunit" placeholder="请输入计量单位"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="cfmaterialspecification">
              <el-input v-model="form.cfmaterialspecification" placeholder="请输入规格型号" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产量" prop="cfproductionquantity">
              <el-input v-model="form.cfproductionquantity" placeholder="请输入生产量" onkeyup="this.value=this.value.match(/\d+\.?\d{0,8}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="fdescription">
              <el-input v-model="form.fdescription" placeholder="请输入描述" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">物料BOM原材料分录信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddBomMaterialhalfentry">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteBomMaterialhalfentry">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="bomMaterialhalfentryList" :row-class-name="rowBomMaterialhalfentryIndex" @selection-change="handleBomMaterialhalfentrySelectionChange" ref="bomMaterialhalfentry">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="原材料编码" prop="cfrawmaterialnumbe" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.cfrawmaterialnumbe" placeholder="请输入原材料编码" readonly/>
              <span class="el-input__suffix">
                <span class="el-input__suffix-inner">
                  <i class="el-input_icon icon el-icon-search"
                     onmousemove="this.style.color='#366EDD'"
                     onmouseout="this.style.color='#919191'"
                     style="font-size: 16px;
                            position: absolute;
                            cursor: pointer;
                            right: 6px;
                            top: 20px;
                            background-color: #ffffff;"
                     @click="openF7('specialmaterial',true,scope.row)"
                  />
                </span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="原材料名称" prop="cfrawmaterialname" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.cfrawmaterialname" placeholder="请输入原材料名称" disabled/>
            </template>
          </el-table-column>
          <el-table-column label="原材料计量单位" prop="cfrawmaterialunit" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.cfrawmaterialunit" placeholder="请输入原材料计量单位" disabled/>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="cfconsumption" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.cfconsumption" placeholder="请输入数量" onkeyup="this.value=this.value.match(/\d+\.?\d{0,8}/);"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.cfverson!='1'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <base-data-view @emitToParent="getF7Data" :tobasedata.sync='basedatadialog'></base-data-view>
  </div>
</template>

<script>
import { listMaterialhalf, getMaterialhalf, delMaterialhalf, addMaterialhalf, updateMaterialhalf } from "@/api/bomcostestimation/basedocument/materialhalf";
import baseDataView from "@/views/bomcostestimation/f7View/baseDataView";
import BOMSM from "@/views/bomcostestimation/basedocument/bomsm";
import { listJob, runJob} from "@/api/monitor/job";

export default {
  name: "Materialhalf",
  components: {"baseDataView": baseDataView,},
  dicts: ['bill_state','bom_wfzbase','bom_seasontype','bom_plant','yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBomMaterialhalfentry: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料BOM表格数据
      materialhalfList: [],
      // 物料BOM原材料分录表格数据
      bomMaterialhalfentryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fname: null,
        fnumber: null,
        cfmaterialnumber: null,
        cfmaterialname: null,
        cfcategoryid: null,
        cfworkshopid: null,
        cfseasontypeid: null,
        cfverson: null,
        cfwfzbaseid: null
      },
      TaskQueryParams: {
        pageNum: 1,
        pageSize: 10,
        jobName: null,
        invokeTarget: 'BomBaseDataTask.getEasMaterialBom',
        jobGroup: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cfmaterialnumber: [
          { required: true, message: "物料编码为空", trigger: "blur" }
        ],
        cfproductionquantity: [
          { required: true, message: "生产量为空", trigger: "blur" }
        ],
        cfconsumption: [
          { required: true, message: "数量为空", trigger: "blur" }
        ],
      },
      basedatadialog:{
        material:{
          //是否显示特殊物料数据对话框
          isMatrialOpen:false,
          //选中的特殊物料信息
          selectedItem:null,
          //弹出的特殊物料是否用于查询
          isMatrialQuery:false,
          //是否为分录
          isEntry: false,
          row:null
        },
        specialmaterial:{
          show: false,
          index:null,
          row:null,
          isEntry:false,
        },
        category:{
          show: false,
          index:null,
          row:null,
          isEntry:false,
        },
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物料BOM列表 */
    getList() {
      this.loading = true;
      listMaterialhalf(this.queryParams).then(response => {
        this.materialhalfList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fid: null,
        fname: null,
        fnumber: null,
        fdescription: null,
        fsimplename: null,
        fcreatorid: null,
        fcreatetime: null,
        flastupdateuserid: null,
        flastupdatetime: null,
        cfmaterialid: null,
        cfmaterialnumber: null,
        cfmaterialname: null,
        cfcategoryid: null,
        cfcategoryname: null,
        cfworkshopid: null,
        cfmaterialunit: null,
        cfmaterialspecification: null,
        cfproductionquantity: null,
        cfverson: '1',
        cfseasontypeid: null,
        cfwfzbaseid: null
      };
      this.bomMaterialhalfentryList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料BOM";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fid = row.fid || this.ids
      getMaterialhalf(fid).then(response => {
        this.form = response.data;
        this.bomMaterialhalfentryList = response.data.bomMaterialhalfentryList;
        this.open = true;
        this.title = "修改物料BOM";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let bomMaterialhalfentryList = this.bomMaterialhalfentryList;
          for (let i = 0; i < bomMaterialhalfentryList.length; i++) {
            let listElement = bomMaterialhalfentryList[i];
            let cfconsumption = listElement.cfconsumption;
            if(cfconsumption==0||cfconsumption==null){
              this.$modal.msgError("分录数量不能为0");
              return
            }
          }
          this.form.bomMaterialhalfentryList = bomMaterialhalfentryList;
          if (this.form.fid != null) {
            updateMaterialhalf(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterialhalf(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fids = row.fid || this.ids;
      this.$modal.confirm('是否确认删除物料BOM编号为"' + fids + '"的数据项？').then(function() {
        return delMaterialhalf(fids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 物料BOM原材料分录序号 */
    rowBomMaterialhalfentryIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 物料BOM原材料分录添加按钮操作 */
    handleAddBomMaterialhalfentry() {
      let obj = {};
      obj.fparentid = "";
      obj.cfrawmaterialid = "";
      obj.cfrawmaterialnumbe = "";
      obj.cfrawmaterialname = "";
      obj.cfrawmaterialunit = "";
      obj.cfconsumption = "";
      this.bomMaterialhalfentryList.push(obj);
    },
    /** 物料BOM原材料分录删除按钮操作 */
    handleDeleteBomMaterialhalfentry() {
      if (this.checkedBomMaterialhalfentry.length == 0) {
        this.$modal.msgError("请先选择要删除的物料BOM原材料分录数据");
      } else {
        const bomMaterialhalfentryList = this.bomMaterialhalfentryList;
        const checkedBomMaterialhalfentry = this.checkedBomMaterialhalfentry;
        this.bomMaterialhalfentryList = bomMaterialhalfentryList.filter(function(item) {
          return checkedBomMaterialhalfentry.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleBomMaterialhalfentrySelectionChange(selection) {
      this.checkedBomMaterialhalfentry = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bomcostestimation/basedocument/materialhalf/export', {
        ...this.queryParams
      }, `materialhalf_${new Date().getTime()}.xlsx`)
    },
    synchronizeData(){
      this.loading = true;
      listJob(this.TaskQueryParams).then(response => {
        let row = response.rows[0];
        runJob(row.jobId, row.jobGroup).then(response =>{
          this.$modal.msgSuccess("执行成功,同步详情可在定时任务日志查看");
          this.loading = false;
        })
      });
    },
    /** f7点击事件 */
    openF7(show,isEntry,row) {
      this.basedatadialog.F7dataType = show;
      switch (show) {
        case 'wfzbase':
          this.basedatadialog.wfzbase.show = !this.basedatadialog.wfzbase.show;
          break;
        case 'materialhalf':
          if(isEntry){
            this.basedatadialog.materialhalf.row = row;
            this.basedatadialog.materialhalf.isEntry = true;
          }
          this.basedatadialog.materialhalf.show = !this.basedatadialog.materialhalf.show;
          break;
        case 'category':
          if(isEntry){
            this.basedatadialog.category.row = row;
            this.basedatadialog.category.isEntry = true;
          }
          this.basedatadialog.category.show = !this.basedatadialog.category.show;
          break;
        case 'specialmaterial':
          if(isEntry){
            this.basedatadialog.specialmaterial.row = row;
            this.basedatadialog.specialmaterial.isEntry = true;
          }
          this.basedatadialog.specialmaterial.show = !this.basedatadialog.specialmaterial.show;
          break;
      }
    },
    /** f7获取值 */
    getF7Data(data) {
      switch (this.basedatadialog.F7dataType) {
        case "category":
          if (data.category != null) {
            this.form.cfcategoryid = data.category.id;
            this.form.cfcategoryname = data.category.name;
          }
          break;
        case "specialmaterial":
          if (data.specialmaterial != null) {
            if(this.basedatadialog.specialmaterial.isEntry){
              this.basedatadialog.specialmaterial.row.cfrawmaterialid = data.specialmaterial.id;
              this.basedatadialog.specialmaterial.row.cfrawmaterialnumbe = data.specialmaterial.materialnumber;
              this.basedatadialog.specialmaterial.row.cfrawmaterialname = data.specialmaterial.materialname;
              this.basedatadialog.specialmaterial.row.cfrawmaterialunit = data.specialmaterial.baseunitname;
              this.basedatadialog.specialmaterial.isEntry = false;
            }else{
              this.form.cfmaterialid = data.specialmaterial.id;
              this.form.cfmaterialnumber = data.specialmaterial.materialnumber;
              this.form.cfmaterialname = data.specialmaterial.materialname;
              this.form.cfmaterialunit = data.specialmaterial.baseunitname;
              this.form.cfmaterialspecification = data.specialmaterial.specifications;
              this.form.fdescription = data.specialmaterial.description;
            }
          }
          this.$refs["form"].validateField("cfmaterialnumber");
          break;
      }
    }
    ,
  },
};
</script>
